//
//  WmcDevEnvironmentVC.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/6/22.
//

import UIKit

// MARK: - [WmcDevEnvironmentVC]

class WmcDevEnvironmentVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "网络环境"
    }

    // Internal

    class WmcDevEnvironmentModel {
        var name: String = ""
        var type: YPWmcManager.EnvironmentType = .develop
        var isSelected: Bool = false
        var host1: String = ""
        var host2: String = ""
    }

    class WmcDevLogModel {
        var name: String = ""
        var isOpen: Bool = false
    }

    override func makeUI() {
        makeNavView(showShadow: false)

        addSubview(tableView)
        addSubview(sureBtn)

        tableView.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom).offset(10)
            make.left.right.equalToSuperview()
        }

        sureBtn.snp.makeConstraints { make in
            make.top.equalTo(tableView.snp.bottom).offset(50)
            make.bottom.equalTo(-Wmc_safeAreaBottom - 30)
            make.height.equalTo(50)
            make.left.equalTo(20)
            make.right.equalTo(-20)
        }
    }

    // Private
    
    private func currentEnvironment() -> YPWmcManager.EnvironmentType {
        var type: YPWmcManager.EnvironmentType = .develop
        
        if testModel.isSelected {
            type = .test
        } else if preReleaseModel.isSelected {
            type = .pre_release
        } else if releaseModel.isSelected {
            type = .release
        }
        
        return type
    }
    
    private func isDataDidChange() -> Bool {
        let result = logModel.isOpen != isOpenLog || currentEnvironment() != environmentType
        return result
    }

    private lazy var isOpenLog: Bool = {
        var isOpen: Bool = false
        if let isOpenCache: Bool = WmcUserdefault.object(forKey: .networkLogSwitch) {
            isOpen = isOpenCache
        }
        return isOpen
    }()

    private lazy var environmentType: YPWmcManager.EnvironmentType = {
        var type: YPWmcManager.EnvironmentType = .develop
        if let typeNum: Int = WmcUserdefault.object(forKey: .networkEnvironment), let typeEnum = YPWmcManager.EnvironmentType(rawValue: typeNum) {
            type = typeEnum
        }
        return type
    }()

    private lazy var logModel: WmcDevLogModel = {
        let model = WmcDevLogModel()
        model.name = "在控制台输出网络日志"
        model.isOpen = isOpenLog
        return model
    }()

    private lazy var devModel: WmcDevEnvironmentModel = {
        let model = WmcDevEnvironmentModel()
        model.name = "开发环境"
        model.type = .develop
        model.isSelected = false
        model.host1 = "https://yupao-develop.vrtbbs.com"
        model.host2 = "http://wmc.superinyang.com"
        return model
    }()

    private lazy var testModel: WmcDevEnvironmentModel = {
        let model = WmcDevEnvironmentModel()
        model.name = "测试环境"
        model.type = .test
        model.isSelected = false
        model.host1 = "https://yupao-test.yupaowang.com"
        model.host2 = "http://wmc.superinyang.com"
        return model
    }()

    private lazy var preReleaseModel: WmcDevEnvironmentModel = {
        let model = WmcDevEnvironmentModel()
        model.name = "预发布环境"
        model.type = .pre_release
        model.isSelected = false
        model.host1 = "https://yupao-master.kkbbi.com"
        model.host2 = "http://wmc-release.superinyang.com"
        return model
    }()

    private lazy var releaseModel: WmcDevEnvironmentModel = {
        let model = WmcDevEnvironmentModel()
        model.name = "线上环境"
        model.type = .release
        model.isSelected = false
        model.host1 = "https://yupao-prod.54xiaoshuo.com"
        model.host2 = "https://wmc.cdzbb.cn"
        return model
    }()

    private lazy var dataSource: [[Any]] = {
        switch environmentType {
        case .develop:
            devModel.isSelected = true
        case .test:
            testModel.isSelected = true
        case .pre_release:
            preReleaseModel.isSelected = true
        case .release:
            releaseModel.isSelected = true
        }

        let arr = [[self.logModel], [self.devModel, self.testModel, self.preReleaseModel, self.releaseModel]]
        return arr
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcDevEnvironmentCell.self, forCellReuseIdentifier: "WmcDevEnvironmentCell")
        view.register(WmcDevLogCell.self, forCellReuseIdentifier: "WmcDevLogCell")
        view.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        view.separatorStyle = .none
        return view
    }()

    private lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("保存", for: .normal)
        btn.setBackgroundImage(UIColor.wmc_yellow_FFC400.yp.uiImage, for: .normal)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        btn.isEnabled = false
        btn.addTarget(self, action: #selector(onSureAction(_:)), for: .touchUpInside)
        return btn
    }()
    
    @objc private func onSureAction(_ sender: UIButton) {
        if logModel.isOpen != isOpenLog {
            WmcUserdefault.save(value: logModel.isOpen, forKey: .networkLogSwitch)
        }
        
        let currentEnvironmentType = currentEnvironment()
        if currentEnvironmentType != environmentType {
            YPWmcManager.switchNetworkEnvironment(currentEnvironmentType)
        }
        
        WmcHudManager.toast("切换成功，正在重启......")
        WmcLoginManager.logout()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            exit(0)
        }
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcDevEnvironmentVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return dataSource.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource[section].count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = dataSource[indexPath.section][indexPath.row]
        if let m = model as? WmcDevEnvironmentModel {
            let cell: WmcDevEnvironmentCell = tableView.dequeueReusableCell(withIdentifier: "WmcDevEnvironmentCell", for: indexPath) as! WmcDevEnvironmentCell
            cell.bindModel(m)
            return cell
        } else if let m = model as? WmcDevLogModel {
            let cell: WmcDevLogCell = tableView.dequeueReusableCell(withIdentifier: "WmcDevLogCell", for: indexPath) as! WmcDevLogCell
            cell.bindModel(m)
            cell.switchClosure = { [weak self] isOn in
                guard let weakSelf = self else { return }
                weakSelf.logModel.isOpen = isOn
                weakSelf.sureBtn.isEnabled = weakSelf.isDataDidChange()
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
            return cell
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataSource[indexPath.section][indexPath.row]
        if let m = model as? WmcDevEnvironmentModel {
            devModel.isSelected = false
            testModel.isSelected = false
            preReleaseModel.isSelected = false
            releaseModel.isSelected = false

            if m.type == .develop {
                devModel.isSelected = true
            } else if m.type == .test {
                testModel.isSelected = true
            } else if m.type == .pre_release {
                preReleaseModel.isSelected = true
            } else if m.type == .release {
                releaseModel.isSelected = true
            }
            self.tableView.reloadData()
        }
        
        sureBtn.isEnabled = isDataDidChange()
    }

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
        return 70
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view: UIView = .init()
        view.backgroundColor = .wmc_grayH22_FFF5E7

        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14, weight: .medium)
        view.addSubview(label)

        if section == 0 {
            label.text = "日志开关"
        } else if section == 1 {
            label.text = "切换网络环境"
        }

        label.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.top.bottom.equalToSuperview()
        }

        return view
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
}
